package server;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**
     * 定义socket监听的端口号
     */
    private int port = 8080;


    private Map<String, HttpServlet> servletMap = new HashMap<String, HttpServlet>();

    /**
     * Minicat 的程序启动入口
     * <p>
     * test URL :
     * http://localhost:8081/demo1/index.html
     * http://localhost:8081/demo2/index.html
     * <p>
     * http://localhost:8081/demo1/lagou
     * http://localhost:8081/demo2/lagou
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置 xml
        loadXml();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );

        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        while (true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    /**
     * 解析 server.xml 文件
     * 1. 拿到 server.xml 中配置的端口号
     * 2. 拿到 server.xml 中配置的绝对路径
     */
    private void loadXml() throws Exception {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        Element rootElement = document.getRootElement();
        // 拿到所有的 service
        List<Element> list = rootElement.selectNodes("//Service");
        if (list == null || list.size() <= 0) return;
        // 这里目前仅取第一个，暂不考虑多配置
        Element element = list.get(0);
        // 拿到 Connector 标签
        Element connector = element.element("Connector");
        // 提取配置文件中设置的 port
        String port = connector.attributeValue("port");
        // 重置 port
        this.port = Integer.parseInt(port);
        // 获取配置文件中指定的绝对路径
        String appBase = element.element("Engine").element("Host").attributeValue("appBase");
        // 将拿到的绝对路径存储到工具类对应属性，用于拼接静态资源文件
        StaticResourceUtil.absolutePath = appBase;
        // 根据拿到的绝对路径，找到具体文件
        File file = new File(appBase);
        // 路径下所有文件夹
        File[] listFiles = file.listFiles();
        // 遍历文件夹（这里每个文件夹都对应一个工程，即都可作为一个工程的根目录）
        for (File projectFile : listFiles) {
            // 解析每个工程的 web.xml 文件
            loadChildrenServlet(projectFile);
        }
    }

    /**
     * 解析 web.xml 文件
     *
     * @param file
     * @throws Exception
     */
    private void loadChildrenServlet(File file) throws Exception {
        String fileAbsolutePath = file.getAbsolutePath();
        // 解析对应某个工程下的 web.xml 文件
        Document document = new SAXReader().read(new File(fileAbsolutePath + "\\web.xml"));
        Element rootElement = document.getRootElement();

        List<Element> selectNodes = rootElement.selectNodes("//servlet");
        for (int i = 0; i < selectNodes.size(); i++) {
            Element element = selectNodes.get(i);
            // <servlet-name>lagou</servlet-name>
            Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
            String servletName = servletnameElement.getStringValue();
            // <servlet-class>server.LagouServlet</servlet-class>
            Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
            String servletClass = servletclassElement.getStringValue();
            // 根据servlet-name的值找到url-pattern
            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
            // /lagou
            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
            // 组装的 url 前 追加 工程名称，
            servletMap.put("/" + file.getName() + urlPattern, (HttpServlet) new MyClassLoader().findClass(fileAbsolutePath + "\\", servletClass).newInstance());
        }
    }
}
